//
//  WKScanView.m
//  ourToken
//
//  Created by wakeup on 2018/6/19.
//  Copyright © 2018年 ourtoken. All rights reserved.
//

#import "WKScanView.h"
#import "WKBaseHeader.h"
#import <AVFoundation/AVFoundation.h>

@interface WKScanView ()

@property (nonatomic, assign) float scanView_X;//扫描框X值

@property (nonatomic, assign) float scanView_Y;//扫描框Y值

@property (nonatomic, assign) float scanView_cornerLength;//扫描框棱角长度

@property (nonatomic, assign) float flashlightBtn_Width;//手电筒按钮高度

@property (nonatomic, assign) float flashlightLab_Height;//手电筒提示语高度

@property (nonatomic, strong) UIImageView *scanLine;//扫描的线

@property (nonatomic, strong) UILabel *hintLabel;//扫描框下方提示文字

@property (nonatomic, strong) UILabel *flashlightLabel;//手电筒提示语

@end

@implementation WKScanView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.scanView_X = (AppManager.width-AppManager.scanView_WH)/2;
        self.scanView_Y = (self.frame.size.height-AppManager.scanView_WH)/2;
        self.scanView_cornerLength = 20;
        self.flashlightBtn_Width = 20;
        self.flashlightLab_Height = 15;
        self.backgroundColor = [UIColor clearColor];
        
        [self addSubview:self.scanLine];
        [self addSubview:self.hintLabel];
        [self addSubview:self.flashlightBtn];
        [self addSubview:self.flashlightLabel];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    //半透明区域
    [[UIColor colorWithWhite:0 alpha:0.5] setFill];
    UIRectFill(rect);
    
    //透明区域
    CGRect scan_rect = CGRectMake(self.scanView_X, self.scanView_Y, AppManager.scanView_WH, AppManager.scanView_WH);
    [[UIColor clearColor] setFill];
    UIRectFill(scan_rect);
    
    //白色边框
    UIBezierPath *borderPath = [UIBezierPath bezierPathWithRect:CGRectMake(self.scanView_X, self.scanView_Y, AppManager.scanView_WH, AppManager.scanView_WH)];
    borderPath.lineCapStyle = kCGLineCapRound;
    borderPath.lineWidth = 0.5;
    [[UIColor whiteColor] set];
    [borderPath stroke];
    
    for (int index = 0; index < 4; ++index) {
        
        UIBezierPath *tempPath = [UIBezierPath bezierPath];
        tempPath.lineWidth = 3;
        [[UIColor greenColor] set];
        
        switch (index) {
                //左上角棱角
            case 0:
            {
                [tempPath moveToPoint:CGPointMake(self.scanView_X + self.scanView_cornerLength, self.scanView_Y)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X, self.scanView_Y)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X, self.scanView_Y + self.scanView_cornerLength)];
            }
                break;
                //右上角
            case 1:
            {
                [tempPath moveToPoint:CGPointMake(self.scanView_X + AppManager.scanView_WH - self.scanView_cornerLength, self.scanView_Y)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X + AppManager.scanView_WH, self.scanView_Y)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X + AppManager.scanView_WH, self.scanView_Y + self.scanView_cornerLength)];
            }
                break;
                //左下角
            case 2:
            {
                [tempPath moveToPoint:CGPointMake(self.scanView_X, self.scanView_Y + AppManager.scanView_WH - self.scanView_cornerLength)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X, self.scanView_Y + AppManager.scanView_WH)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X + self.scanView_cornerLength, self.scanView_Y + AppManager.scanView_WH)];
            }
                break;
                //右下角
            case 3:
            {
                [tempPath moveToPoint:CGPointMake(self.scanView_X + AppManager.scanView_WH - self.scanView_cornerLength, self.scanView_Y + AppManager.scanView_WH)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X + AppManager.scanView_WH, self.scanView_Y + AppManager.scanView_WH)];
                [tempPath addLineToPoint:CGPointMake(self.scanView_X + AppManager.scanView_WH, self.scanView_Y + AppManager.scanView_WH - self.scanView_cornerLength)];
            }
                break;
            default:
                break;
        }
        [tempPath stroke];
    }
}

#pragma mark - 扫描动画
- (void)stratScanLineAnimation {
    [self.scanLine.layer removeAllAnimations];
    CABasicAnimation *lineAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    
    lineAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, self.scanLine.frame.size.width - self.scanLine.frame.size.height, 1)];
    
    lineAnimation.duration = 4;
    lineAnimation.repeatCount = HUGE;
    [self.scanLine.layer addAnimation:lineAnimation forKey:@"ScanLineAnmationKey"];
    self.scanLine.layer.speed = 2.0;
}

- (void)pauseScanLineAnimation {
    //取出当前时间，转成动画暂停的时间
    CFTimeInterval pauseTime = [self.scanLine.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    //设置动画的时间偏移量，指定时间偏移量的目的是让动画定格在该时间点的位置
    self.scanLine.layer.timeOffset = pauseTime;
    //将动画的运行速度设置为0， 默认的运行速度是1.0
    self.scanLine.layer.speed = 0;
}

#pragma mark - 是否显示手电筒
- (void)showFlashlightWithAnimated:(BOOL)animated {
    if (animated) {
        [UIView animateWithDuration:0.6 animations:^{
            self.flashlightLabel.alpha = 1.0;
            self.flashlightBtn.alpha = 1.0;
            self.hintLabel.alpha = 0;
        } completion:^(BOOL finished) {
            self.flashlightBtn.enabled = YES;
        }];
    }else
    {
        self.flashlightLabel.alpha = 1.0;
        self.flashlightBtn.alpha = 1.0;
        self.hintLabel.alpha = 0;
        self.flashlightBtn.enabled = YES;
    }
}

- (void)hideFlashlightWithAnimated:(BOOL)animated {
    self.flashlightBtn.enabled = NO;
    if (animated) {
        [UIView animateWithDuration:0.6 animations:^{
            self.flashlightLabel.alpha = 0;
            self.flashlightBtn.alpha = 0;
            self.hintLabel.alpha = 1.0;
        } completion:^(BOOL finished) {
        }];
    }else
    {
        self.hintLabel.alpha = 1.0;
        self.flashlightLabel.alpha = 0;
        self.flashlightBtn.alpha = 0;
    }
}

#pragma mark - 设置手电筒开关
- (void)setFlashlightOn:(BOOL)on {
    self.flashlightBtn.selected = on;
    self.flashlightLabel.text = on ? @"轻触关闭":@"轻触照亮";
    
    // ppExt：不能使用_device：无相机权限不能打开
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //判断是否有闪光灯
    if (![device hasTorch]) {
        return;
    }
    
    [device lockForConfiguration:nil];
    if (on) {
        [device setTorchMode:AVCaptureTorchModeOn];
    }
    else {
        [device setTorchMode:AVCaptureTorchModeOff];
    }
    [device unlockForConfiguration];
}

#pragma mark - 懒加载UI
- (UIImageView *)scanLine {
    if (_scanLine == nil) {
        _scanLine = [[UIImageView alloc]initWithFrame:CGRectMake((self.frame.size.width-AppManager.scanView_WH)/2, (self.frame.size.height-AppManager.scanView_WH)/2, AppManager.scanView_WH, 8)];
        _scanLine.image = [UIImage imageNamed:@"ScanLine"];
    }
    return _scanLine;
}

- (UILabel *)hintLabel {
    if (_hintLabel == nil) {
        _hintLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.scanView_Y + AppManager.scanView_WH, self.frame.size.width, 50)];
        _hintLabel.textAlignment = NSTextAlignmentCenter;
        _hintLabel.textColor = [UIColor lightGrayColor];
        _hintLabel.text = @"将二维码/条码放入框内，即可自动扫描";
        _hintLabel.font = [UIFont systemFontOfSize:12];
    }
    return _hintLabel;
}

- (UIButton *)flashlightBtn {
    if (!_flashlightBtn) {
        _flashlightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _flashlightBtn.frame = CGRectMake((self.frame.size.width - self.flashlightBtn_Width)/2, self.scanView_Y + AppManager.scanView_WH - 15 - self.flashlightLab_Height - self.flashlightBtn_Width, self.flashlightBtn_Width, self.flashlightBtn_Width);
        _flashlightBtn.enabled = NO;
        _flashlightBtn.alpha = 0;
        [_flashlightBtn addTarget:self action:@selector(flashlightClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"Flashlight_Off"] forState:UIControlStateNormal];
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"Flashlight_On"] forState:UIControlStateSelected];
    }
    return _flashlightBtn;
}

- (UILabel *)flashlightLabel {
    if (_flashlightLabel == nil) {
        _flashlightLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.scanView_X, self.scanView_Y + AppManager.scanView_WH - 10 - self.flashlightLab_Height, AppManager.scanView_WH, self.flashlightLab_Height)];
        _flashlightLabel.font = [UIFont systemFontOfSize:12];
        _flashlightLabel.textColor = [UIColor whiteColor];
        _flashlightLabel.text = @"轻触照亮";
        _flashlightLabel.alpha = 0;
        _flashlightLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _flashlightLabel;
}

#pragma mark - 手电筒点击事件
- (void)flashlightClicked:(UIButton *)button {
    button.selected = !button.selected;
    [self setFlashlightOn:self.flashlightBtn.selected];
}

@end
